WEBAPP['pageKokology'] = function() {
	QUIZ.init();
};

var QUIZ = {
	totalQuizes : 2,
	curIdx : -1,
	quizType : 0,
	results : null,

	load : function() {
		$.post('/app/quiz/data/vi_kokology_source', {
			'-not-trim-space' : 1
		}, function(text) {
			var parts = text.split('=+=');
			var quizes = parts[0].split('\n|');

			$('#totalQuestions').text(QUIZ.totalQuizes = quizes.length);
			var html = [];
			var qParts = null;
			
			$.each(quizes, function(i, quiz) {
				html.push('<div class="quiz" id="quiz-', i, '">');

				qParts = $.trim(quiz).split('\n');
				html.push('<p class="question">', qParts[1], '</p>');

				for (var j = 2; j < qParts.length; j++) {
					html.push('<label><input type="radio" name="q-', i, '" value="', qParts[j].substring(0, qParts[j].indexOf('.')), '"> ', $.trim(qParts[j].substring(3)), '</label>');
				}

				html.push('</div>');
			});

			$('#quizes').html(html.join(''));
			QUIZ.ready();

			var results = parts[1].trim().split('\n||', 2);
			QUIZ.quizType = parseInt(results[0].substring(0, results[0].indexOf(' ')), 10);
			switch (QUIZ.quizType) {
			case 1:
				QUIZ.parseRs1(results[1]);
				break;
			}

		});
	},

	parseRs1 : function(results) {
		var rs = [];
		$.each(results.split('\n|'), function(i, row) {
			var item = row.trim().split('\n*');
			rs[rs.length] = item;
			console.log(item);
			
		});
		QUIZ.results = rs;
	},

	init : function() {
		QUIZ.load();

		$('#helpForm').submit(function() {
			QUIZ.start();
			return false;
		});

		$('#page-quiz').on('click touch', '.quiz-open input', function() {
			var T = $(this);
			var choice = parseInt(T.val(), 10);

			T = T.parent().addClass('checked').parent().addClass('quiz-checked');

			// show liền kết quả
			var rs = QUIZ.results[QUIZ.curIdx][choice].trim();
			rs = rs.substring(3).replace('\n', '<br/>');
			T.append('<p class="result-desc">' + rs + '</p>');

			// cho bấm next
			$('#quizFooter').show();
			if (QUIZ.curIdx == QUIZ.totalQuizes - 1) {
				$('#page-quiz').addClass('quiz-finish');
			}

			// clear
			T = null;
		}).on('click touch', '.next-button', function() {
			QUIZ.nextQuiz();
		});

		QUIZ.intro();
	},

	nextQuiz : function() {
		++QUIZ.curIdx;

		$('.quiz-open').removeClass('quiz-open');

		if (QUIZ.curIdx < QUIZ.totalQuizes) {
			$('#quiz-' + QUIZ.curIdx).addClass('quiz-open');
			$('#currentQuestion').text(QUIZ.curIdx + 1);
			$('#quizFooter').hide();
		} else {
			QUIZ.finish();
		}
	},

	ready : function() {
		$('#helpForm').show();
	},
	intro : function() {
		QUIZ.showHelp();
	},

	start : function() {
		this.showPage('#page-quiz');
		
		QUIZ.curIdx = -1;
		QUIZ.nextQuiz();
	},

	showHelp : function() {
		this.showPage('#page-help');
	},

	showPage : function(page) {
		$('.app-page').hide();
		$(page).show();
	},
};